package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.sky.constant.MessageConstant.UNKNOWN_ERROR;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获唯一约束异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result duplicateSqlException(DuplicateKeyException ex) {
        log.error("异常信息：{}", ex.getMessage());
        //ex.getMessage()  ： Duplicate entry 'guanyu' for key 'idx_username'
        String exceptionMsg = ex.getMessage();
        if (exceptionMsg.contains("Duplicate entry")) {
            String username = exceptionMsg.split(" ")[9];
            String errormsg = "用户名重复：【" + username.replace("'", "") + "】";
            return Result.error(errormsg);
        }
        return Result.error(UNKNOWN_ERROR);
    }

    /**
     * 捕获所有系统异常（最后保底的）
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result systemException(Exception ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(UNKNOWN_ERROR);
    }

}
